package cn.topcodes.tcsf.wechat.service.ops;

import cn.topcode.unicorn.utils.JsonUtil;
import cn.topcode.unicorn.utils.http.HttpResp;
import cn.topcode.unicorn.utils.http.HttpUtil;
import cn.topcodes.tcsf.admin.service.ops.OpsConnectedEvent;
import cn.topcodes.tcsf.admin.service.ops.OpsService;
import cn.topcodes.tcsf.admin.service.ops.SubmitResult;
import cn.topcodes.tcsf.wechat.service.WechatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 *
 * @author Unicorn
 * @date 2018/6/23
 */
@Component
public class WechatOpsService implements ApplicationListener<OpsConnectedEvent> {

    public static final String SUBMIT_URL = "http://%s:%d/api/server/submit-wechat-property";

    private boolean isPropertySubmited = false;

    @Autowired
    private WechatUserService wechatUserService;

    @Autowired
    private OpsService opsService;

    @Scheduled(cron = "0 0 1 * * ? ")
    public void clear() {
        opsService.clearSubmit();
        this.isPropertySubmited = false;
    }

    @Override
    public void onApplicationEvent(OpsConnectedEvent event) {
        if(isPropertySubmited) {
            return;
        }
        String url = String.format(SUBMIT_URL, event.getOpsServerHost(), event.getOpsServerHttpPort());
        SubmitWechatProperty submitWechatProperty = new SubmitWechatProperty();
        submitWechatProperty.setNo(event.getNo());
        submitWechatProperty.setWechatUserCount(wechatUserService.countAll());
        HttpResp resp = HttpUtil.post(submitWechatProperty, url);
        if(resp != null && resp.getStatusCode() == 200) {
            SubmitResult result = JsonUtil.parse(resp.getBody(), SubmitResult.class);
            if(result != null && "OK".equals(result.getCode())) {
                isPropertySubmited = true;
                return;
            }
        }
        throw new IllegalStateException("提交微信服务信息失败");
    }
}
